﻿using Company.Core.Helper;
using Company.Sqlite.Models;
using FastReport;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Printing;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using 无人值守地磅称重系统.Interfaces;

namespace 无人值守地磅称重系统.Services
{
    public class PrintService : IPrintService
    {
        public ISession Session { get; }
        public IConfigService ConfigService { get; }

        public PrintService(ISession session, IConfigService configService)
        {
            Session = session;
            ConfigService = configService;
        }

        public void Print(Data entity, bool preview = false)
        {
            if(entity== null) { return; }
            PrintDialog printDialog = new PrintDialog();
            PrintQueue printQueue = printDialog.PrintQueue;
            if(printQueue == null)
            {
                Session.Show("未发现打印机");
                return;
            }
            if (!File.Exists(ConfigService.SystemConfig.Template))
            {
                Session.Show("未发现磅单模板");
                return;
            }
            App.Current.Dispatcher.Invoke(new Action(() => {

                try
                {
                    DataTable dataTable = JsonHelper.toDataTable(new List<Data>() { entity });
                    using(Report report= new Report())
                    {
                        report.Load(ConfigService.SystemConfig.Template);
                        report.RegisterData(dataTable, "Data");
                        report.Prepare();
                        if (preview)
                        {
                            report.ShowPrepared(true); // 预览
                        }
                        else
                        {
                            report.PrintSettings.ShowDialog = true;
                            report.Print(); // 打印
                        }
                    }
                }
                catch (Exception ex)
                {
                   Session.Show(ex.Message);
                    Log.Error(ex.Message + ex.StackTrace);
                }
            }));
        }
    }
}
